import java.util.List;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.LinkedBlockingDeque;


public class Worker implements Runnable{

	LinkedBlockingDeque<Mash> unstable;
	private Maschen maschen;
	Mash aktMash;
	boolean brk = false;
	
	public Worker(LinkedBlockingDeque<Mash> work, Maschen maschen){
		this.unstable = work;
		this.maschen=maschen;
		}
	
	@Override
	public void run() {
		while (!Thread.interrupted() && !unstable.isEmpty()){
//			Knoten akt = work.pollFirst(); //krit
			aktMash = unstable.pollFirst();
			if(aktMash == null) break;
			brk = false;
			for(Knoten akt : aktMash.getkList()){
				if (brk) break;
			List<Knoten> vorList=akt.getVorganger();

			
//			ConcurrentHashMap<Mash,List> mashMap= new ConcurrentHashMap<Mash, List>();
			
			for(Knoten pre : vorList){
				if (brk) break;
				List<Knoten> mashList= new CopyOnWriteArrayList<Knoten>();
				Mash preMash= pre.getMash();
//				preMash.add(pre);
				for(Knoten knotenAusVorMash: preMash.getkList()){
					if(!aktMash.zeigtAufMash(knotenAusVorMash)){
						mashList.add(knotenAusVorMash);
					}
				}
//				System.out.println("aktMash: " + aktMash + "mashList: " + mashList);
				if (!mashList.isEmpty()){						//TODO Krit!
				preMash.removeKnList(mashList);
//				maschen.checkMash(preMash);
				Mash neu = new Mash(pre.getCapacity(),mashList);
				maschen.add(neu);
//				if(maschen.containsMash(preMash)){
					preMash.setUnstable();
//				}
				neu.setUnstable();
//				if(maschen.containsMash(aktMash)){
//					unstable.add(aktMash);
//				}
				if(preMash==aktMash){
				brk = true;
//				System.out.println("break");
				}
				}
			}
			aktMash.setStable();

		}
		}
	}

}
